package com.candy.security.jwt.service;

import cn.hutool.crypto.SmUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.candy.security.jwt.entity.CandyUserdetails;
import com.candy.security.jwt.entity.LoginUser;
import com.candy.sys.entity.Role;
import com.candy.sys.entity.User;
import com.candy.sys.service.IUserRoleService;
import com.candy.sys.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@Component
public class CustomUserDetailsService implements UserDetailsService
{
	public static String UsernameSplit = "~";

	@Autowired
	private IUserService userService;

	@Autowired
	private IUserRoleService userRoleService;

	@Value("${token.defalut.password:123456}")
	private String defalutPassword;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
	{
		if(StringUtils.isEmpty(username))
		{
			throw new UsernameNotFoundException("未获取到用户名");
		}
		username = username.trim();
		// 通过用户名从数据库获取用户信息
		List<User> userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getLoginName, username));
		if (userList == null || userList.isEmpty())
		{
			if(username.contains(UsernameSplit))
			{
				String[] userNameAndField = username.split(UsernameSplit);
				if(userNameAndField.length==2)
				{
					userList = userService.list(new QueryWrapper<User>().eq(userNameAndField[1], userNameAndField[0]));
				}
			}
		}
		if (userList == null || userList.isEmpty())
		{
			userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getLoginName, "demo"));
		}
		if (userList.size() > 1)
		{
			throw new UsernameNotFoundException("用户不明确");
		}
		User user = userList.get(0);
		List<Role> roles = userRoleService.getRolesByUserId(user.getId());
		// 角色集合
		List<String> authoritieList = new ArrayList<>();
		// 角色必须以`ROLE_`开头，数据库中没有，则在这里加
		roles.forEach(role -> {
			//需自己编写数据库查询权限数据的mapper和service
			if(StringUtils.isNotEmpty(role.getAuthorities()))
			{
				String[] authoritys = role.getAuthorities().split(",");
				for (String item : authoritys)
				{
					authoritieList.add(item);
				}
				authoritieList.add("ROLE_" + role.getRoleCode());
			}
		});
		if(StringUtils.isEmpty(user.getPassword()))
		{
			user.setPassword(SmUtil.sm3(user.getLoginName()+defalutPassword));
		}
		LoginUser loginUser = new LoginUser(authoritieList);
		BeanUtils.copyProperties(user,loginUser);
		return new CandyUserdetails(loginUser, user.getPassword());
	}

}